
package com.shop.cloud.common.es.config;

import co.elastic.clients.elasticsearch.ElasticsearchAsyncClient;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.springframework.boot.autoconfigure.elasticsearch.ElasticsearchProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import jakarta.annotation.Resource;

/**
 * @author 
 * https://blog.csdn.net/Mrzhuangr/article/details/128425473
 * RestHighLevelClient 初始化
 */
@Slf4j
@Configuration
public class ElasticSearchConfig {

	@Resource
	private ElasticsearchProperties elasticsearchProperties;

	@Bean
	public ElasticsearchClient elasticsearchClient(){
		ElasticsearchTransport transport = getElasticsearchTransport();
		return new ElasticsearchClient(transport);
	}

	@Bean
	public ElasticsearchAsyncClient elasticsearchAsyncClient(){
		ElasticsearchTransport transport = getElasticsearchTransport();
		return new ElasticsearchAsyncClient(transport);
	}

	private ElasticsearchTransport getElasticsearchTransport() {
		final CredentialsProvider credentialsProvider =
				new BasicCredentialsProvider();
		credentialsProvider.setCredentials(AuthScope.ANY,
				new UsernamePasswordCredentials(elasticsearchProperties.getUsername(), elasticsearchProperties.getPassword()));
		String uri = elasticsearchProperties.getUris().get(0);
		uri = uri.replaceAll("http://", "").replaceAll("https://", "");
		String[] s = uri.split(":");
		String host = s[0];
		int port = s.length >= 2 ? Integer.parseInt(s[1]) : 80;
		RestClientBuilder builder = RestClient.builder(
				new HttpHost(host, port, "http"))
				.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder
						.setDefaultCredentialsProvider(credentialsProvider))
				.setRequestConfigCallback(requestConfigBuilder -> {
							//设置连接超时时间
							int timeOut = (int) elasticsearchProperties.getConnectionTimeout().toMillis();
							requestConfigBuilder.setConnectTimeout(timeOut);
							requestConfigBuilder.setSocketTimeout(timeOut);
							return requestConfigBuilder;
						});
		RestClient restClient = builder.build();
		return new RestClientTransport(restClient,new JacksonJsonpMapper());
	}
}
